package com.atguigu.gmall.pay.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.mq.MqConst;
import com.atguigu.gmall.mq.to.OrderPayedSkuDetailTo;
import com.atguigu.gmall.mq.to.OrderPayedSuccessMessageTo;
import com.atguigu.gmall.pay.config.AppAlipayConfig;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamsVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    AlipayClient alipayClient;
    @Autowired
    AppAlipayConfig appAlipayConfig;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderFeignClient orderFeignClient;

    /**
     * vo收集到页面支付请求的核心信息
     * @param vo
     * @return
     */
    @Override
    public String payOrder(PayParamsVo vo) throws Exception {
        //1.创建一个支付请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(appAlipayConfig.getReturn_url());
        alipayRequest.setNotifyUrl(appAlipayConfig.getNotify_url());

        //2.设置支付请求的请求体
        String json = new ObjectMapper().writeValueAsString(vo);
        alipayRequest.setBizContent(json);

        //3.请求，响应的是一个html内容,调用支付宝的支付功能
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //result //代表的是支付宝返回的二维码支付页

        //返回支付宝的二维码支付页
        return result;
    }

    /**
     * 检查订单是否支付
     * @param outTradeNo
     * @return
     */
    @Override
    public Boolean queryOrderStatus(String outTradeNo) throws Exception{

        //1、设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //请二选一设置
        Map<String,String> map = new HashMap<>();
        map.put("out_trade_no",outTradeNo);
        String asString = new ObjectMapper().writeValueAsString(map);
        alipayRequest.setBizContent(asString);

        //请求
        AlipayTradeQueryResponse response = alipayClient.execute(alipayRequest);
        if("10000".equals(response.getCode()) && response.getTradeStatus().equals("TRADE_SUCCESS")){
            //支付成功
            return true;
        }

        return false;
    }

    @Override
    public void sendPaySuccessMessage(String out_trade_no) throws JsonProcessingException {
        //TODO 2、给对列发送的内容; JSON串
        OrderInfo orderInfo = orderFeignClient.getOrderInfoWithDetailsByOutTradeNo(out_trade_no);
        List<OrderPayedSkuDetailTo> detailTos = new ArrayList<>();

        //1、准备mq消息内容，封装订单信息
        OrderPayedSuccessMessageTo message = new OrderPayedSuccessMessageTo();
        BeanUtils.copyProperties(orderInfo,message);
        message.setOrderId(orderInfo.getId());
        message.setOrderBody(orderInfo.getOrderDetailList().get(0).getSkuName());
        message.setPaymentWay("2"); //在线支付

        //2、封装订单的所有商品信息
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            OrderPayedSkuDetailTo detailTo = new OrderPayedSkuDetailTo();
            BeanUtils.copyProperties(orderDetail,detailTo);
            detailTos.add(detailTo);
        }
        message.setDetails(detailTos);

        //TODO 1、队列名： queue.ware.stock；  需要知道哪个交换机用哪个路由键绑定了这个对象
        //队列名：MqConst.QUEUE_WARE_STOCK
        //交换机名：MqConst.EXCHANGE_DIRECT_WARE_STOCK
        //路由键： MqConst.ROUTING_WARE_STOCK
        // @RabbitListener(bindings=声明的关系)：也会自动创建出队列交换机和绑定关系
        // @Bean也会创建出来
        /**
         *     @RabbitListener(bindings = @QueueBinding(
         *             value = @Queue(value = MqConst.QUEUE_WARE_STOCK, durable = "true"),
         *             exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_STOCK, type = ExchangeTypes.DIRECT, durable = "true"),
         *             key = {MqConst.ROUTING_WARE_STOCK}
         *     ))
         */
        String string = new ObjectMapper().writeValueAsString(message);
        //给库存消息发送了消息
        rabbitTemplate.convertAndSend(MqConst.EXCHANGE_DIRECT_WARE_STOCK,MqConst.ROUTING_WARE_STOCK,string);
    }
}
